#include "SoundWrapper.h"
#include "SDL2/SDL_mixer.h"
#include "SoundException.h"
#include <map>

typedef std::map<std::string, Mix_Chunk*> Sounds;
static Mix_Music* music = NULL;
static Sounds sounds;

void SoundWrapper::init()
{
    Mix_OpenAudio(22050, AUDIO_S16, 2, 512);
    sounds["click"] = Mix_LoadWAV("resources/instantdown.wav");
    sounds["bang"] = Mix_LoadWAV("resources/removerow.wav");
    sounds["swoosh"] = Mix_LoadWAV("resources/swoosh.wav");
}

void SoundWrapper::quit()
{
    for (Sounds::iterator it = sounds.begin(); it != sounds.end(); ++it)
    {
        Mix_FreeChunk(it->second);
    }
    sounds.clear();
    Mix_CloseAudio();
}

void SoundWrapper::playMusic(const std::string& path)
{
    music = Mix_LoadMUS(path.c_str());
    if (music != NULL)
    {
        Mix_PlayMusic(music, -1);
    }
    else
    {
        throw SoundException("Music failed to load.");
    }
}

void SoundWrapper::stopMusic()
{
    Mix_HaltMusic();
    Mix_FreeMusic(music);
}

void SoundWrapper::playSound(const std::string& soundId)
{
    Sounds::iterator it = sounds.find(soundId);
    if (it != sounds.end())
    {
        Mix_VolumeChunk(it->second, 32);
        Mix_PlayChannel(-1, it->second, 0);
    }
}

SoundWrapper::SoundWrapper()
{
}

SoundWrapper::~SoundWrapper()
{
}

